#/bin/bash                                                                                                                   
set -x                                                                                                                        
BASE_DIR=`cd $(dirname $0);pwd`

fouction_vars(){
        #Service domain
        SERVICE_DOMAIN=`nslookup ${POD_IP} |grep "name" |awk '{print $4}' |grep "^[A-Z,a-z]" |awk -F '.' '{print $2"."$3".svc.cluster.local"}'`
        #All of Service PodIP
        SERVICE_ALL_NODE_IP=`nslookup ${SERVICE_DOMAIN} |grep -A 1 Name |awk '/Address/ {print $2}'`
        STATEFUL_NAME=`hostname |awk -F '-' '{print $1}'`
        PASSWORD=`grep  "requirepass" "$(find / -name "redis.conf")" |grep -v "#" |awk '/requirepass/ {print $2}'`
        PORT=`grep  "port" "$(find / -name "redis.conf")" |grep -v "#" |awk '{print $2}'`
}

fouction_get_hosts(){
        [ -f "${BASE_DIR}/hosts" ] && rm -rf ${BASE_DIR}/hosts
        for IP in ${SERVICE_ALL_NODE_IP};do
                HOSTNAME=`nslookup ${IP} |grep "name" |awk '{print $4}' |grep "^[A-Z,a-z]" |awk -F '.' '{print $1}'`
                echo "${IP} ${HOSTNAME}" >>${BASE_DIR}/hosts
        done  
}

fouction_get_cluster_and_node_message(){
        for IP in ${SERVICE_ALL_NODE_IP};do

                NUMBER=`redis-cli -a ${PASSWORD} -h ${IP} cluster nodes |wc -l`

                if [ "${NUMBER}" -lt '3' ];then
                        HOSTNAME_NUMBER=`grep "${IP}" ${BASE_DIR}/hosts  |awk -F '[-|" "]' '{print $NF}'`
                        if [ "$((${HOSTNAME_NUMBER}%2))" -eq '0' ];then
                                MASTER_IP_PORT="${MASTER_IP_PORT} ${IP}:${PORT}"
                        else
                                SLAVE_IP_PORT="${SLAVE_IP_PORT} ${IP}:${PORT}"
                        fi
                else
                        IN_CLUSTER_IP="${IN_CLUSTER_IP} ${IP}"
                        echo ${IN_CLUSTER_IP}
                fi
        done
}

fouction_check_cluster(){
        MAX_CHECK_COUNTS=30
        RANDOM_IP_IN_CLUSTER=$(echo ${IN_CLUSTER_IP} |cut -d " " -f `echo $((RANDOM%6))`)
        TIME=`date +%s`
        count=1
        redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT}

        until [ "$?" -eq '0' ] || [ "$(($(date +%s)-${TIME}))" -ge "${MAX_CHECK_COUNTS}" ];do
                sleep 1
                let count++
                redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT}
        done

        if [ "${count}" -lt "${MAX_CHECK_COUNTS}" ];then
                return 0
        else
                return 1
        fi
}

fouction_create_cluster(){
        echo "yes" |redis-cli -a ${PASSWORD} --cluster create ${MASTER_IP_PORT} ${SLAVE_IP_PORT} --cluster-replicas 1
        redis-cli -a ${PASSWORD} -h $(echo ${SLAVE_IP_PORT}|awk -F ':' '{print $1}') --cluster check $(echo ${SLAVE_IP_PORT}|awk '{print $NF}')
        if [ "$?" -eq '0' ];then
                echo "Cluster created successfully"
        else
                echo "Cluster created failed"
        fi

}
fouction_add_node(){

        fouction_check_cluster
        if [ "$?" -eq '0'  ] && [ ! -z "${MASTER_IP_PORT}" ];then
                for ADD_MASTER in ${MASTER_IP_PORT};do

                        redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER} --cluster add-node ${ADD_MASTER} ${RANDOM_IP_IN_CLUSTER}:${PORT}
                        fouction_check_cluster
                        if [ "$?" -eq '0'  ];then
                                echo "Add node ${ADD_MASTER} to cluster ${RANDOM_IP_IN_CLUSTER}:${POR} successful"
                        else
                                echo "Add node ${ADD_MASTER} to cluster ${RANDOM_IP_IN_CLUSTER}:${POR} failed" && exit 201
                        fi

                        IN_CLUSTER_IP_NOW=`redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT} |awk -F '[:|" "]' '/[A-Z]:/ {print $4}'`

                        for MEET_IP in ${IN_CLUSTER_IP_NOW};do

                                if [ "$(redis-cli -a  ${PASSWORD} -h $(echo ${ADD_MASTER} |awk -F ':' '{print $1}') cluster meet ${MEET_IP} ${PORT})" == 'OK' ];then
                                        echo "NewMasterIP:${ADD_MASTER} meet ${MEET_IP} ${PORT} successful"
                                else
                                        echo "NewMasterIP:${ADD_MASTER} meet ${MEET_IP} ${PORT} failed" && exit 201
                                fi
                        done

                        fouction_check_cluster
                        if [ "$?" -eq '0' ];then
                                MY_ID=`redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT} |grep "${ADD_MASTER}$" |awk '{print $2}'`
                                RESHARD_NUMBER=`expr 16384 / $((${POD_REPLICAS_NUMBER}/2))`

                                redis-cli -a ${PASSWORD}  --cluster reshard ${RANDOM_IP_IN_CLUSTER}:${PORT} --cluster-from all \
                                --cluster-to ${MY_ID} --cluster-slots ${RESHARD_NUMBER} --cluster-yes

                                fouction_check_cluster
                                if [ "$?" -eq '0'  ];then
                                        echo "Check success. New master ${ADD_MASTER} reshard successful"
                                else
                                        echo "Check failed. Maybe New master ${ADD_MASTER} reshard failed" && exit 201
                                fi

                        else
                                echo "Reshard check. Check cluster failed"
                        fi
                done
        else
                echo "Add node check. Check cluster failed or var MASTER_IP_PORT  none"
        fi
}

fouction_replication(){

        fouction_check_cluster
        if [ "$?" -eq '0' ] && [ ! -z "${SLAVE_IP_PORT}" ];then
                MASTER_NO_SLAVE=`redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT} |awk '/0 slaves/ {print $1}'`

                if [ "`echo ${SLAVE_IP_PORT} |awk '{print NF}'`" -ge "`echo ${MASTER_NO_SLAVE} |awk '{print NF}'`" ];then

                        echo "Replicate begin"

                        flag=1
                        for MASTER_IP in ${MASTER_NO_SLAVE};do
                                SLAVE_IP=`echo ${SLAVE_IP_PORT} |cut -d " " -f ${flag}`
                                MASTER_ID=`redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT} |grep "${MASTER_IP}$" |awk '{print $2}'`

                                redis-cli -a ${PASSWORD} --cluster add-node ${SLAVE_IP} ${RANDOM_IP_IN_CLUSTER}:${PORT} \
                                --cluster-slave --cluster-master-id ${MASTER_ID}

                                redis-cli -a ${PASSWORD} -h ${RANDOM_IP_IN_CLUSTER}  --cluster check ${RANDOM_IP_IN_CLUSTER}:${PORT} |grep "0 slaves" |grep "${MASTER_IP}"
                                if [ "$?" -ne '0' ];then
                                        echo "Replication:${SLAVE_IP} Master:${MASTER_IP} successful" && let flag++
                                else
                                        echo "Replication:${SLAVE_IP} Master:${MASTER_IP} failed"
                                fi
                        done
                else
                        echo "Replication. Do not have enough slave node"
                fi
        else
                echo "Replication. Check cluster failed or do not have slave"
        fi
}

fouction_exec(){

        fouction_get_hosts

        POD_REPLICAS_NUMBER=$(cat ${BASE_DIR}/hosts |wc -l)

        if [ "${POD_REPLICAS_NUMBER}" -ge '6' ] && [ "$((${POD_REPLICAS_NUMBER}%2))" -eq '0' ];then

                fouction_get_cluster_and_node_message

                MASTER_AND_SLAVE_NUMBER="$((`echo ${SLAVE_IP_PORT} |awk '{print NF}'`+`echo ${MASTER_IP_PORT} |awk '{print NF}'`))"

                if [ "${MASTER_AND_SLAVE_NUMBER}" -eq "${POD_REPLICAS_NUMBER}" ];then

                        fouction_create_cluster

                elif [ "${MASTER_AND_SLAVE_NUMBER}" -ne "${POD_REPLICAS_NUMBER}" ] && [ ! -z "${MASTER_IP_PORT}" ];then

                        fouction_add_node
                        fouction_replication

                elif [ "${MASTER_AND_SLAVE_NUMBER}" -ne "${POD_REPLICAS_NUMBER}" ] && [ ! -z "${SLAVE_IP_PORT}" ];then

                        fouction_replication
                else
                        echo "New node is '0'" ; exit 201
                fi
        else
                echo "Node not enougth or Pod replicas not even number" ; exit 201
        fi
}

fouction_vars
fouction_exec
rm -rf ${BASE_DIR}/hosts
